package beanstao.util.random;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import beanstao.util.Util;
import beanstao.util.reflect.Mirror;

public abstract class EnumRandom<T extends Enum<?>> implements IRandom<T>
{

	private RecurArrayRandom<T> r;

	@SuppressWarnings("unchecked")
	protected EnumRandom()
	{
		try
		{
			Class<T> type = (Class<T>) Mirror.getTypeParams(this.getClass())[0];
			Field[] fields = type.getFields();
			List<T> list = new ArrayList<T>(fields.length);
			for (Field f : fields)
			{
				if (f.getType() == type)
				{
					list.add((T) f.get(null));
				}
			}
			T[] ens = (T[]) Array.newInstance(type, list.size());
			this.r = new RecurArrayRandom<T>(list.toArray(ens));
		}
		catch (Exception e)
		{
			throw Util.wrapThrow(e);
		}
	}

	public T next()
	{
		return this.r.next();
	}

}
